<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if(!class_exists('Api_hb_bluemember')){
    class Api_hb_bluemember extends CI_Controller {

        protected $_action = '';

        protected $_distance = 325;

        protected $_base_url = 'https://bmapi.pxene.com';
        // protected $_base_url = 'https://www.bluemembers.com.cn/api';
        protected $_client_id = 'opc07e5ad3f3fe297e';
        protected $_client_secret = '931efbdc1ba967e8b72c9e4a15a07d46';

        public function __construct(){
            parent::__construct();
            $this->load->model('Apilogmodel','m_api_log');
            $this->load->model('Usermodel','m_user');
            $this->load->model('Appmodel','m_app');
            $this->load->model('configmodel','m_config');
            $this->load->model('Bluemembercustomermodel','m_customer');
            $this->load->model('Bluememberlotterytimemodel','m_lottery_time');
            $this->load->model('Bluemembercardtimemodel','m_card_time');
            $this->load->database();

            if(is_string($this->uri->rsegments[2]) && stripos($this->uri->rsegments[2], 'api') === 0) {
                return;
            }
        }

        public function __destruct() {
            // $this->session->unset_userdata($this->_action);
            // //api开头的不存
            if(is_string($this->uri->rsegments[2]) && stripos($this->uri->rsegments[2], 'api') === 0) {
            	$this->db->close();
                return;
            }
            $customer = $this->session->userdata('bluemember_customer');
            $info = $this->input->post();
            $result = $this->response->getResult();
            @$this->m_api_log->createApiLog(array(
                'ip_address' => $this->input->ip_address(),
                'customer_id' => empty($customer) ? 0 :  $customer['customer_id'],
                'request_uri' => $_SERVER['REQUEST_URI'],
                'post_data' => json_encode($info,JSON_UNESCAPED_UNICODE),
                'result_data' => json_encode($result,JSON_UNESCAPED_UNICODE),
                'api_log_time_create' => NOW,
                'ua' => empty($_SERVER['HTTP_USER_AGENT']) ? '' : $_SERVER['HTTP_USER_AGENT'],
                // 'terminal' => TERMINAL_WEIXIN,
            ));

            $this->db->close();
        }

        private function _getToken() {
            $this->load->driver('cache', array('adapter' => 'file'));
            $cache_file = 'token.cache';
            $content = $this->cache->get($cache_file);

            if(empty($content)) {
                $this->load->library('rest');
                $url = $this->_base_url.'/OAuth/Token';
                $content = $this->rest->post($url
                    ,array('client_id' => $this->_client_id
                        , 'client_secret' => $this->_client_secret
                        ,'scope' => 'basic'
                        ,'grant_type' => 'client_credentials'));
                $expires_in = $content->expires_in;
                $content = json_encode($content);
                $this->cache->save($cache_file,  $content,  $expires_in - 1000);
            }
            $content = json_decode($content,true);
            $token = $content['token_type'].' '.$content['access_token'];
            return $token;
        }

        public function test1() {
            // echo json_encode($this->_getMemberInfo('dcd03f4b-630b-4322-a911-ec278e566ed8'));
            echo json_encode($this->_getMemberInfo('D66DC427-FCEC-446C-8A7E-4622773F1709'));
        }

        public function test2() {
            // echo json_encode($this->_getMemberInfo('dcd03f4b-630b-4322-a911-ec278e566ed8'));
            $user_id = 'D66DC427-FCEC-446C-8A7E-4622773F1709';
            $this->load->library('rest');
            $token = $this->_getToken();
            $url = $this->_base_url.'/api/CustomCard/GetUserCustomCardList?merchantType=1&userId='.$user_id;
            $this->rest->http_header('Authorization',$token);
            $content = $this->rest->get($url,array());
            echo json_encode($content);
        }


        public function getToken() {
        	$token = $this->_getToken();
        	header('Content-Type: application/javascript');
        	echo 'var global_authorization="'.$token.'";';
        }

        private function _getMemberInfo($bluemember_user_id) {
            $this->load->library('rest');
            $token = $this->_getToken();
            $url = $this->_base_url.'/api/Account/MemberInfo?id='.$bluemember_user_id;
            $this->rest->http_header('Authorization',$token);
            $content = $this->rest->post($url
                ,array());
            return $content;
        }  

        private function _checkMember($member,$checkChezhu = false) {
            $member = json_decode(json_encode($member),true);
            if(empty($member['Code']) || $member['Code'] != 200) {
                $this->response->setDetail('还不是Bluemembers用户!');
                $this->response->responseExit();
            }
            if($checkChezhu) {
                if(intval($member['Content']['SystemMType']) <= 1) {
                    $this->response->setDetail('还不是Bluemembers车主用户!');
                    $this->response->responseExit();
                }
            }
        }

        public function initCustomer() {
            $this->validate->setRule('bluemember_user_id','string');
            $this->validate->setRule('bluemember_phone','string');
            if(!$this->validate->run($this->input->post(),true)){
                $this->response->setDetail($this->validate->getMessage());
                $this->response->responseExit();
            }
            $info = $this->validate->getResult();

            $member = $this->_getMemberInfo($info['bluemember_user_id']);
            $this->_checkMember($member);
            

            $customer = $this->m_customer->getCustomerByBluememberUserid($info['bluemember_user_id']);
            if(empty($customer)) {
                $customer_id = $this->m_customer->createCustomer(array(
                    'bluemember_user_id' => $info['bluemember_user_id'],
                    'bluemember_phone' => $info['bluemember_phone'],
                    'customer_status' => STATUS_ACTIVE,
                    'customer_time_create' => NOW,
                ));
                if($customer_id == 0) {
                    $this->response->setDetail('创建用户失败!');
                    $this->response->responseExit();
                }
                $customer = $this->m_customer->getCustomer($customer_id);
            }

            $customer['lottery_available'] = $this->m_customer->checkLotteryAvailable($customer['customer_id']);

            global $g_bluemember_gift;
            $customer['gift_name'] = id2name($customer['gift_type'],$g_bluemember_gift);
            $this->session->set_userdata('bluemember_customer',$customer);

            unset($customer['gift_type_tmp']);
            $this->response->setSuccess();
            $this->response->setAddon($customer);
            $this->response->responseExit();
        }

        public function drawnLottery() {
            $this->validate->setRule('bluemember_user_id','string');
            if(!$this->validate->run($this->input->post(),true)){
                $this->response->setDetail($this->validate->getMessage());
                $this->response->responseExit();
            }
            $info = $this->validate->getResult();

            $member = $this->_getMemberInfo($info['bluemember_user_id']);
            $this->_checkMember($member,true);

            $customer = $this->m_customer->getCustomerByBluememberUserid($info['bluemember_user_id']);
            if(empty($customer)) {
                $this->response->setDetail('未找到用户!');
                $this->response->responseExit();
            }

            $lottery_available = $this->m_customer->checkLotteryAvailable($customer['customer_id']);
            if(!$lottery_available) {
                $this->response->setDetail('您已抽过奖!');
                $this->response->responseExit();
            }

            $customer_id = $customer['customer_id'];
            $lottery_result = 0;
            $lottery_time_id=0;
            $lotteryTime = $this->m_lottery_time->getCurrentLotteryTimeRate();
            if(!empty($lotteryTime)) {
                $lottery_time_id = $lotteryTime['lottery_time_id'];
                if(!$this->m_customer->checkHasLotteryGift($customer['customer_id'])) {
                    $lottery_time_gift1_rate = floatval($lotteryTime['lottery_time_gift1_rate']);
                    $lottery_time_gift2_rate = floatval($lotteryTime['lottery_time_gift2_rate']);
                    $lottery_time_gift3_rate = floatval($lotteryTime['lottery_time_gift3_rate']);
                    $lottery_time_gift4_rate = floatval($lotteryTime['lottery_time_gift4_rate']);
                    $lottery_time_gift5_rate = floatval($lotteryTime['lottery_time_gift5_rate']);
                }

                $baseNum = 1000000000;
                $num = rand(1,$baseNum);

                if($customer['gift_type'] == 0) {
                    $rate = 0;
                    $rate += $lottery_time_gift1_rate;
                    if($lottery_result == 0 && $lottery_time_gift1_rate > 0 && $num <= $rate*$baseNum
                        && intval($lotteryTime['lottery_time_gift1_count']) > intval($lotteryTime['lottery_time_gift1_count_drawn'])) {
                        $lottery_result = 1;
                    }
                    $rate += $lottery_time_gift2_rate;
                    if($lottery_result == 0 && $lottery_time_gift2_rate > 0 && $num <= $rate*$baseNum
                        && intval($lotteryTime['lottery_time_gift2_count']) > intval($lotteryTime['lottery_time_gift2_count_drawn'])) {
                        $lottery_result = 2;
                    }
                    $rate += $lottery_time_gift3_rate;
                    if($lottery_result == 0 && $lottery_time_gift3_rate > 0 && $num <= $rate*$baseNum
                        && intval($lotteryTime['lottery_time_gift3_count']) > intval($lotteryTime['lottery_time_gift3_count_drawn'])) {
                        $lottery_result = 3;
                    }
                    $rate += $lottery_time_gift4_rate;
                    if($lottery_result == 0 && $lottery_time_gift4_rate > 0 && $num <= $rate*$baseNum
                        && intval($lotteryTime['lottery_time_gift4_count']) > intval($lotteryTime['lottery_time_gift4_count_drawn'])) {
                        $lottery_result = 4;
                    }
                    $rate += $lottery_time_gift5_rate;
                    if($lottery_result == 0 && $lottery_time_gift5_rate > 0 && $num <= $rate*$baseNum
                        && intval($lotteryTime['lottery_time_gift5_count']) > intval($lotteryTime['lottery_time_gift5_count_drawn'])) {
                        $lottery_result = 5;
                    }
                }
            }

            //记录数据库
            $this->m_customer->createLotteryHistory(array(
                'customer_id' => $customer['customer_id'],
                'lottery_time_id' => $lottery_time_id,
                'gift_type' => $lottery_result,
                'lottery_time_time_create' => NOW,
            ));


            $this->m_customer->updateCustomerLotteryCount($customer['customer_id']);

            if($lottery_result > 0) {
                $this->m_customer->editCustomer(array(
                    'customer_id' => $customer['customer_id'],
                    'gift_type' => $lottery_result,
                    'lottery_time_id' => $lottery_time_id,
                    'customer_time_lottery' => NOW,
                ));
                $this->m_lottery_time->updateLotteryCountDrawn($lottery_time_id,$lottery_result);
            }


            

            global $g_bluemember_gift;
            $customer = $this->m_customer->getCustomer($customer_id);
            $customer['gift_type'] = $lottery_result;
            $customer['gift_name'] = id2name($lottery_result,$g_bluemember_gift);
            $customer['lottery_available'] = $this->m_customer->checkLotteryAvailable($customer['customer_id']);
            $this->session->set_userdata('bluemember_customer',$customer);

            unset($customer['gift_type_tmp']);

            $this->response->setSuccess();
            $this->response->setAddon($customer);
            $this->response->responseExit();
        }

        public function submitAddress() {
            $this->validate->setRule('bluemember_user_id','string');
            $this->validate->setRule('customer_name','string');
            $this->validate->setRule('customer_name','message','请填您的姓名');
            $this->validate->setRule('customer_phone','string');
            $this->validate->setRule('customer_phone','message','请填您的手机号');
            $this->validate->setRule('customer_address','string');
            $this->validate->setRule('customer_address','message','请填您的收货地址');
            if(!$this->validate->run($this->input->post(),true)){
                $this->response->setDetail($this->validate->getMessage());
                $this->response->responseExit();
            }
            $info = $this->validate->getResult();

            $member = $this->_getMemberInfo($info['bluemember_user_id']);
            $this->_checkMember($member,true);

            $customer = $this->m_customer->getCustomerByBluememberUserid($info['bluemember_user_id']);
            if(empty($customer)) {
                $this->response->setDetail('未找到用户!');
                $this->response->responseExit();
            }
            if($customer['gift_type'] == 0) {
                $this->response->setDetail('您还未中奖，不能提交地址!');
                $this->response->responseExit();
            }

            if(!preg_match("/^1[0-9]\d{9}$/i", $info['customer_phone'])){
                $this->response->setDetail('请输入正确的手机号码!');
                $this->response->responseExit();
            }
            
            $info['customer_id'] = $customer['customer_id'];
            $this->m_customer->editCustomer($info);

            $this->session->set_userdata('bluemember_customer',$customer);
            
            $this->response->setSuccess();
            $this->response->setDetail('收货地址提交成功!');
            $this->response->responseExit();
        }

        public function getGiftCustomerList() {
            $assist = array(
                'select' => 'bluemember_phone, gift_type' ,
                'where' => array('gift_type >' => '0'),
            );
            list($list,$count) = $this->m_customer->getCustomerListSection($assist);
            global $g_bluemember_gift;
            foreach ($list as $key => $value) {
                $phone = $value['bluemember_phone'];
                $new_phone = (strlen($phone) > 3 ? substr($phone, 0,3) : '').'****'.(strlen($phone) > 7 ? substr($phone, 7) : '');
                $list[$key]['bluemember_phone'] = $new_phone;
                $list[$key]['gift_name'] = id2name($value['gift_type'],$g_bluemember_gift);
                unset($list[$key]['gift_type']);
            }
            $this->response->setSuccess();
            $this->response->setItems($list);
            $this->response->responseExit();
        }

        public function test() {
        	header("Access-Control-Allow-Origin: *");
        	$this->response->setSuccess();
            $this->response->setDetail('提交成功!');
            $this->response->responseExit();
        }

        public function receiveCard() {
            $this->validate->setRule('bluemember_user_id','string');
            $this->validate->setRule('bluemember_phone','string');
            $this->validate->setRule('source','string');
            if(!$this->validate->run($this->input->post(),true)){
                $this->response->setDetail($this->validate->getMessage());
                $this->response->responseExit();
            }
            $info = $this->validate->getResult();

            $member = $this->_getMemberInfo($info['bluemember_user_id']);
            $this->_checkMember($member);
            

            $customer = $this->m_customer->getCustomerByBluememberUserid($info['bluemember_user_id']);
            if(empty($customer)) {
                $customer_id = $this->m_customer->createCustomer(array(
                    'bluemember_user_id' => $info['bluemember_user_id'],
                    'bluemember_phone' => $info['bluemember_phone'],
                    'customer_status' => STATUS_ACTIVE,
                    'customer_time_create' => NOW,
                ));
                if($customer_id == 0) {
                    $this->response->setDetail('创建用户失败!');
                    $this->response->responseExit();
                }
                $customer = $this->m_customer->getCustomer($customer_id);
            }

            $this->load->library('rest');
            $token = $this->_getToken();
            $url = $this->_base_url.'/api/CustomCard/GetUserCustomCardList?merchantType=1&userId='.$info['bluemember_user_id'];
            $this->rest->http_header('Authorization',$token);
            $content = $this->rest->get($url,array());
            $content = json_decode(json_encode($content),true);
            if($content['Code'] != 200) {
                $this->response->setDetail('卡券用户获取列表失败!');
                $this->response->responseExit();
            }

            $cardKeys = array('ReceivedCustomCardList','UsedCustomCardList','ExpiredCustomCardList');

            global $g_cardlist;
            $card = array();
            foreach ($g_cardlist as $key => $value) {
                foreach ($cardKeys as $k1 => $v1) {
                    foreach ($content['Content'][$v1] as $k2 => $v2) {
                        if($v2['CardType'] == $value['CardType']) {
                            $card = $value;
                            break;
                        }
                    }
                    if(!empty($card)) break;
                }
                if(!empty($card)) break;
            }

            if(!empty($card)) {
                $card['is_received'] = true;
                $this->response->setSuccess();
                $this->response->setAddon($card);
                $this->response->responseExit();
            }

            $cardTime = $this->m_card_time->getCurrentCardTimeRate();
            $cardId = 0;
            $card_time_id = 0;
            if(!empty($cardTime)) {
                $card_time_id = $cardTime['card_time_id'];
                if(!$this->m_customer->checkHasLotteryGift($customer['customer_id'])) {
                    $card_time_gift1_rate = floatval($cardTime['card_time_gift1_rate']);
                    $card_time_gift2_rate = floatval($cardTime['card_time_gift2_rate']);
                }

                $baseNum = 1000000000;
                $num = rand(1,$baseNum);

                $rate = 0;
                $rate += $card_time_gift1_rate;
                if($cardId == 0 && $card_time_gift1_rate > 0 && $num <= $rate*$baseNum
                    && intval($cardTime['card_time_gift1_count']) > intval($cardTime['card_time_gift1_count_drawn'])) {
                    $cardId = 1;
                }
                $rate += $card_time_gift2_rate;
                if($cardId == 0 && $card_time_gift2_rate > 0 && $num <= $rate*$baseNum
                    && intval($cardTime['card_time_gift2_count']) > intval($cardTime['card_time_gift2_count_drawn'])) {
                    $cardId = 2;
                }
            }
            if($cardId == 0) {
                $cardId = 3;
            }
            $card = $g_cardlist[$cardId];
            $card['is_received'] = false;

            $url = $this->_base_url.'/api/CustomCard/GetSummerUserCustomCardNo?cardType='.$card['CardType'].'&userId='.$info['bluemember_user_id']
                        .'&phone='.$customer['bluemember_phone'].'&source='.$info['source'];
            $this->rest->http_header('Authorization',$token);
            $content = $this->rest->get($url,array());
            $content = json_decode(json_encode($content),true);

            if($content['IsSuccess'] !== true) {
                $this->response->setDetail(!empty($content['Message']) ? $content['Message']: '卡券库存不足!');
                $this->response->setAddon($content);
                $this->response->responseExit();
            }

            $this->m_customer->createCardHistory(array(
                'card_time_id' => $card_time_id,
                'card_type_id' => $cardId,
                'card_type' => $card['CardType'],
                'card_name' => $card['CardName'],
                'customer_id' => $customer['customer_id'],
                'card_time_time_create' => NOW,
                'source' => $info['source'],
            ));
            $this->m_card_time->updateCardCountDrawn($card_time_id,$cardId);

            $this->response->setSuccess();
            $this->response->setAddon($card);
            $this->response->responseExit();
        }

        public function unbindWeixin() {
            $openid = 'omXbSjmJoMRPaNrZ4hX0xezMRA-c';
            $userId = '14dc807a-4d0d-42fd-b019-5574cbb79334';
            $this->load->library('rest');
            $token = $this->_getToken();
            $url = 'https://www.bluemembers.com.cn/weixin/WxUserBmUser/BindUser/api/Account/UnbindWX';
            $this->rest->http_header('Authorization',$token);
            $content = $this->rest->post($url,array(
                'OpenId' => $openid,
                'UserId' => $userId,
            ));
            echo json_encode($content);
        }

        public function bindWeixin() {
            $openid = 'omXbSjmJoMRPaNrZ4hX0xezMRA-c';
            $userId = '4d9a1c13-f9fb-41dd-859a-23d3a6eb9147';

            // 4d9a1c13-f9fb-41dd-859a-23d3a6eb9147
            $this->load->library('rest');
            $token = $this->_getToken();
            $url = 'https://www.bluemembers.com.cn/weixin/WxUserBmUser/BindUser?openId='.$openid.'&userId='.$userId;
            // echo $url;
            $this->rest->http_header('Authorization',$token);
            $content = $this->rest->post($url);
            echo json_encode($content);
        }

        public function dbview() {
            die();
            $data['desc'] = '清除bluemembers数据';
            $data['ctrlName'] = $this->uri->rsegments[1];
            $this->load->view('zm/clear_db',$data);
        }
        public function clearDb(){
            die();
            $this->db->truncate('bluemember_lottery_history'); 
            $this->db->truncate('bluemember_customer'); 
            

            $this->response->setSuccess();
            $this->response->setDetail('清除成功!');
            $this->response->responseExit();
        }

    }
    
}